import api, { shouldUseCefSharp, handleSuccessResponse } from './TabAxios/base'
import { handleGroupRequests } from './TabAxios/groups'
import { handleMonitorRequests } from './TabAxios/monitor'
import { handleSettingsRequests } from './TabAxios/settings'
import { handleDeviceRequests } from './TabAxios/device'
import { handleDownloadRequests } from './TabAxios/download'
import { handleEdgeRequests } from './TabAxios/edge'
import { handleUserRequests } from './TabAxios/user'

// === 请求拦截器 ===
api.interceptors.request.use(
    async request => {
        // 检查是否需要使用CefSharp处理
        if (shouldUseCefSharp(request)) {
            const response = await handleCefSharpRequest(request)
            if (response) {
                return Promise.reject({ isCefsharp: true, data: response })
            }
        }
        return request
    }
)

// === 响应拦截器 ===
api.interceptors.response.use(
    response => {
        // 处理正常响应
        handleSuccessResponse(response)
        return response.data
    },
    error => {
        // 处理CefSharp响应
        if (error && error.isCefsharp) {
            return Promise.resolve(error.data)
        }
        return Promise.reject(error)
    }
)

// === CefSharp请求处理统一入口 ===
async function handleCefSharpRequest(request) {
    const { method, url, data, params } = request
    console.log('🔍 [API] CefSharp请求:', { method, url, data, params })

    // 提取URL路径的第一个段落用于路由判断
    const pathMatch = url.match(/\/([^/]+)/)
    const firstPathSegment = pathMatch ? pathMatch[1] : ''

    // === 分组相关接口 ===
    if (firstPathSegment === 'groups') {
        return await handleGroupRequests(method, url, data, params)
    }

    // === 监控相关接口 ===
    if (firstPathSegment === 'monitor') {
        return await handleMonitorRequests(method, url, data, params)
    }

    // === 设置相关接口 ===
    if (firstPathSegment === 'settings') {
        return await handleSettingsRequests(method, url, data, params)
    }

    // === 设备相关接口 ===
    if (firstPathSegment === 'device') {
        return await handleDeviceRequests(method, url, data, params)
    }

    // === 下载相关接口 ===
    if (firstPathSegment === 'download') {
        return await handleDownloadRequests(method, url, data, params)
    }

    // === Edge相关接口 ===
    if (firstPathSegment === 'edge') {
        return await handleEdgeRequests(method, url, data, params)
    }

    // === 用户相关接口 ===
    if (firstPathSegment === 'user') {
        return await handleUserRequests(method, url, data, params)
    }

    return null
}

export default api 